/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.core.service.impl;

import com.lvyh.lightframe.transaction.common.config.TransactionApplicationConfig;
import com.lvyh.lightframe.transaction.common.constant.TransactionConstant;
import com.lvyh.lightframe.transaction.core.event.TransactionEventProducer;
import com.lvyh.lightframe.transaction.core.service.TransactionLogRepositoryService;
import com.lvyh.lightframe.transaction.core.service.TransactionMessageService;
import com.lvyh.lightframe.transaction.core.service.TransactionRecoverService;
import com.lvyh.lightframe.transaction.core.task.TransactionRecoverTask;
import com.lvyh.lightframe.transaction.common.thread.NamedThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class TransactionRecoverServiceImpl implements TransactionRecoverService {

    /**
     * Transaction log data storage service
     */
    @Autowired
    private TransactionLogRepositoryService transactionLogRepositoryService;

    /**
     * Transaction event sender service
     */
    @Autowired
    private TransactionEventProducer transactionEventProducer;

    /**
     * Transaction log message queue service
     */
    @Autowired
    private TransactionMessageService transactionMessageService;

    private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5, new NamedThreadFactory("transaction-recover"));

    public void start(TransactionApplicationConfig transactionApplicationConfig) {

        Runnable command = new TransactionRecoverTask(transactionMessageService, transactionLogRepositoryService, transactionEventProducer);
        //Create scheduled task: execute 30 seconds after the first execution, and then execute the next task 120 seconds after the end of each execution
        executor.scheduleWithFixedDelay(command, 30, TransactionConstant.RETRIED_PERIOD, TimeUnit.SECONDS);
    }

}
